//
//  TableViewController.m
//  UI_17_homework_Preview_NSFileManage
//
//  Created by li cheng on 16/8/6.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "TableViewController.h"
#import "TableViewCell.h"
#import "ViewController.h"
#import "DetailsViewController.h"
#import "ContactInformation.h"
@interface TableViewController ()<ViewControllerDelegate>
@property (nonatomic, strong) NSMutableArray *nameArray;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) ContactInformation *contactInformation;
@property (nonatomic, strong) NSString *pathContactInformation;
@property (nonatomic, strong) NSMutableArray *arrayContact;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, strong) NSMutableArray *mArrOfSelectIndex;
@property (nonatomic, strong) NSMutableIndexSet *mSet;
@property (nonatomic, strong) DetailsViewController *receive;
@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    
    // 添加编辑按钮
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    // 创建数组
    _nameArray = [NSMutableArray array];
    _arrayContact = [NSMutableArray array];
    _mArrOfSelectIndex = [NSMutableArray array];
    _mSet = [NSMutableIndexSet indexSet];
    // 找到沙盒路径
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", [array lastObject]);
    // 找到存放联系人信息的路径
    self.pathContactInformation = [[array lastObject] stringByAppendingPathComponent:@"contactInformation.plist"];
    _arrayContact = [NSKeyedUnarchiver unarchiveObjectWithFile:_pathContactInformation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _arrayContact.count;
}
#pragma mark tableView 代理 cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 创建tableView
     TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    //取值
    ContactInformation *information = [_arrayContact objectAtIndex:indexPath.row];
    cell.textLabel.text = information.name;
    return cell;
}
#pragma mark - cell的编辑状态
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
#pragma mark - cell进入编辑状态
- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
    [super setEditing:editing animated:animated];
    if (editing) {
        NSLog(@"编辑");
    } else {
        // 删除数据源
        [self.arrayContact removeObjectsAtIndexes:_mSet];
        if (_mSet.count != 0) {
            BOOL isSuccess = [NSKeyedArchiver archiveRootObject:self.arrayContact toFile:_pathContactInformation];
            if (isSuccess) {
                NSLog(@"删除成功");
            } else {
                NSLog(@"删除失败");
            }
            // 删除cell
            [self.tableView deleteRowsAtIndexPaths:_mArrOfSelectIndex withRowAnimation:UITableViewRowAnimationTop];
            [_mArrOfSelectIndex removeAllObjects];
            [_mSet removeAllIndexes];
        }
    }
}
#pragma mark - 当点击的时候执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     NSLog(@"@@@@@@@@@@@@@@@@@@@@@@%s", __FUNCTION__);
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:_pathContactInformation];
    ContactInformation *information = [array objectAtIndex:indexPath.row];
    _receive.information = information;
    NSLog(@"我传过去的名字:%@", information);
    self.indexPath = indexPath;
    self.index = indexPath.row;
    if (self.editing) {
        NSLog(@"选中我了");
        [self.mArrOfSelectIndex addObject:indexPath];
        [self.mSet addIndex:indexPath.row];
        return;
    }
}
#pragma mark - 取消选择
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.editing) {
        [self.mArrOfSelectIndex removeObject:indexPath];
        [self.mSet removeIndex:indexPath.row];
    }
}
#warning 有点问题,我注释的地方会崩溃,我的sb没有关联,窝草了
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:@"SendValue"]){
        _receive = segue.destinationViewController;
        NSLog(@"@@@@@@@@@@@@@@@@@@@@@@%s", __FUNCTION__);
    }
    if ([segue.identifier isEqualToString:@"AddContact"]) {
        ViewController *vc = segue.destinationViewController;
        vc.delegate = self;
    }
}

#pragma mark - 自己创建的点击 保存 按钮代理方法
- (void)imageName:(NSString *)iamgeName name:(NSString *)name contantWay:(NSString *)contantWay address:(NSString *)address{
    // 保存我所编辑的联系人信息
    ContactInformation *information = [[ContactInformation alloc] init];
    information.imageName = iamgeName;
    information.name = name;
    information.contactWay = contantWay;
    information.address = address;
    [_arrayContact addObject:information];
    // 归档,序列化
    BOOL isWrite = [NSKeyedArchiver archiveRootObject:_arrayContact toFile:_pathContactInformation];
    if (isWrite) {
        NSLog(@"存入成功");
    } else {
        NSLog(@"保存失败");
    }
    [self.tableView reloadData];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
